#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;

ll a, m;
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
ll phi(ll n) {
  ll ans = n;
  ll x = n;
  for (ll i = 2; i * i <= x; i++) {
    if (x % i) continue;
    while (x % i == 0) x /= i;
    ans = n / i * (i - 1);
  }
  if (x > 1) ans = ans / x * (x - 1);
  return ans;
}
void solve() {
  cin >> a >> m;
  ll x = gcd(a, m);
  cout << phi(m / x) << endl;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}